#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from ops.devops.utils.util_config import get_config


my_user = 'xiaobo.du@yueyanglearning.com'  # 收件人邮箱账号，我这边发送给自己


def mail(*args, **kwargs):
    try:
        conf = get_config('smtp')
        smtp_server = conf.get('smtp_server')
        smtp_user = conf.get('smtp_user')
        smtp_passwd = conf.get('smtp_passwd')
        receivers = kwargs.get('receivers')
        subject = kwargs.get('subject')
        content = kwargs.get('content')
        files = kwargs.get('files')
        _subtype = kwargs.get('_subtype', 'plain')

        # 创建一个带附件的实例
        message = MIMEMultipart()
        message['From'] = Header(smtp_user, 'utf-8')
        message['To'] = Header(','.join(receivers), 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')

        # 发送正文，采用plain模式
        message.attach(MIMEText(content, _subtype, 'utf-8'))
        # 发送附件
        # 构造附件，支持多个附件
        if files:
            for file in files:
                file_ = os.path.join('uploads', file.name)
                with open(file_, 'wb') as f:
                    for item in file.chunks():
                        f.write(item)
                att1 = MIMEText(open(file_, 'rb').read(), 'base64', 'utf-8')
                att1["Content-Type"] = 'application/octet-stream'
                # 这里的filename可以任意写，写什么名字，邮件中显示什么名字
                att1["Content-Disposition"] = f"attachment; filename={file.name}"
                message.attach(att1)
        if conf.get('smtp_ssl'):
            server = smtplib.SMTP_SSL(smtp_server, conf.get('smtp_port', 465))  # 发件人邮箱中的SMTP服务器，端口默认465
        else:
            server = smtplib.SMTP(smtp_server, conf.get('smtp_port', 25))  # 发件人邮箱中的SMTP服务器，端口默认25
        server.login(smtp_user, smtp_passwd)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(smtp_user, receivers, message.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
        data = {'msg': '发送成功', 'code': 2000}
    except Exception as e:
        data = {'msg': f'发送失败，原因:{e}', 'code': 400}
    return data
